<script setup lang="ts">
import { toPng } from 'html-to-image'
import { ref } from 'vue'
import { useStore } from '@/stores'
import fetch from '@/utils/fetch'

const store = useStore()
const { editor } = storeToRefs(store)

const dialogVisible = ref(false)

interface FormType {
  title: string
  desc: string
  thumb: string
  content: string
  contentImg: string
}

const form = ref<FormType>({
  title: ``,
  desc: ``,
  thumb: ``,
  content: ``,
  contentImg: ``,
})

async function preOpen() {
  // Reset form to ensure it's initialized
  form.value = {
    title: ``,
    desc: ``,
    thumb: ``,
    content: ``,
    contentImg: ``,
  }
}

declare global {
  interface Window {
    syncPost: (data: { thumb: string, title: string, desc: string, content: string }) => void
    $syncer: any
  }
}

async function post() {
  await downloadAsCardImage()
  if (!editor.value)
    return
  const md = editor.value?.getValue() ?? ``

  dialogVisible.value = false
  console.log(form.value)
  fetch.post(`/system//mk/article/new`, {
    ...form.value,
    content: md,
  }).then((_res) => {
    console.log(_res)
  })
}

function onUpdate(val: boolean) {
  if (!val) {
    dialogVisible.value = false
  }
}

// 下载卡片
async function downloadAsCardImage() {
  const el = document.querySelector(`#output-wrapper>.preview`)! as HTMLElement
  const dataUrl = await toPng(el, {
    backgroundColor: `#fff`,
    skipFonts: true,
    pixelRatio: Math.max(window.devicePixelRatio || 1, 2),
    style: {
      margin: `0`,
    },
  })

  debugger
  // 提取 base64 数据（去掉 data:image/png;base64, 前缀）
  const base64Data = dataUrl.split(`,`)[1]
  // 发送到 Spring Boot 后端
  const response = await fetch.post(`/system/file/base64`, {
    name: form.value.title,
    imageData: base64Data,
  })
  debugger
  form.value.contentImg = response.url
  return response
}
onBeforeMount(() => {
})
</script>

<template>
  <Dialog v-model:open="dialogVisible" @update:open="onUpdate">
    <DialogTrigger>
      <Button v-if="!store.isMobile" variant="outline" @click="preOpen">
        发布至ERP
      </Button>
    </DialogTrigger>
    <DialogContent>
      <DialogHeader>
        <DialogTitle>发布至ERP</DialogTitle>
      </DialogHeader>
      <div class="w-full flex items-center gap-4">
        <Label for="thumb" class="w-10 text-end">
          封面
        </Label>
        <Input id="thumb" v-model="form.thumb" placeholder="自动提取第一张图" />
      </div>
      <div class="w-full flex items-center gap-4">
        <Label for="title" class="w-10 text-end">
          标题
        </Label>
        <Input id="title" v-model="form.title" placeholder="自动提取第一个标题" />
      </div>
      <div class="w-full flex items-start gap-4">
        <Label for="desc" class="w-10 text-end">
          描述
        </Label>
        <Textarea id="desc" v-model="form.desc" placeholder="自动提取第一个段落" />
      </div>

      <DialogFooter>
        <Button variant="outline" @click="dialogVisible = false">
          取 消
        </Button>
        <Button @click="post">
          确 定
        </Button>
      </DialogFooter>
    </DialogContent>
  </Dialog>
</template>
